<template>
    <view class="page">
        <view class="feedback-body" >
            <textarea placeholder="请输入您的评价..." style="border-bottom:1px solid   #F1F1F3;" v-model="sendDate.comment" class="feedback-textare" />
        </view>
        <choose :count="count"  :imgList="imgList"  :imgUploaded="imgUploaded" @changes="fileChange(arguments)"></choose>
		<cpimg ref="cpimg" @result="cpimgOk" @err="cpimgErr" :fixOrientation="true" :size="500" :maxWidth="1000" :ql="0.9"></cpimg>
        <view class='feedback-title feedback-star-view'>
            <text>商品评分</text>
            <view class="feedback-star-view">
                <text class="feedback-star" v-for="(value,key) in stars" :key="key" :class="key < sendDate.goodsGrade ? 'active' : ''" @tap="chooseStar(value, 0)"></text>
            </view>
        </view>
		<view class='feedback-title feedback-star-view'>
		    <text>服务评分</text>
		    <view class="feedback-star-view">
		        <text class="feedback-star" v-for="(value,key) in stars" :key="key" :class="key < sendDate.serviceGrade ? 'active' : ''" @tap="chooseStar(value, 1)"></text>
		    </view>
		</view>
		<view class='feedback-title feedback-star-view'>
		    <text>物流评分</text>
		    <view class="feedback-star-view">
		        <text class="feedback-star" v-for="(value,key) in stars" :key="key" :class="key < sendDate.logisticsGrade ? 'active' : ''" @tap="chooseStar(value, 2)"></text>
		    </view>
		</view>
        <button type="default" class="feedback-submit" @tap="send">发布</button>
    </view>
</template>

<script>
    import choose from "@/components/image/choose.vue"
    import cpimg from "@/components/cpimg/cpimg.vue"
	import otherApis from '@/common/services/other.js';
	import base from '@/common/services/base.js'; // 导入http中创建的axios实例
	import {getCookie} from '@/utils/cookiesUtil.js'
	import { mapState } from 'vuex';
	const difference = require("lodash.difference") 
	const cloneDeep = require("lodash.clonedeep")
	const apiUrl = base.test;
    export default {
        name:'newsPublish',
        components:{
        	choose,
			cpimg
        },
		computed: {
		 	...mapState(['orderInfo']),
		},
        data() {
            return {
                isYasuo:true,
                count:6,
                maxwh:280,
                quality:1, 
                msgContents: ["界面显示错乱", "启动缓慢，卡出翔了", "UI无法直视，丑哭了", "偶发性崩溃"],
                stars: [1, 2, 3, 4, 5],
                imgList: [],
				imgUploaded: [],
                sendDate: {
					goodsGrade: 0,
					serviceGrade: 0,
					logisticsGrade: 0,
                    comment: "",
                }
            }
        },
        onLoad() {
        },
        methods: {
            compressImg(e){
              console.log(e)
			   for(let i in this.imgList){
					let imgFile = this.imgList[i]
					this.getImageInfo(imgFile)
				}
            },
			// 获取图片信息
			getImageInfo(src) {
				let _this = this
				console.log('src:', src)
				uni.getImageInfo({
					src,
					success(res) {
						console.log('压缩前', res)
						let canvasWidth = res.width //图片原始长宽
						let canvasHeight = res.height
						let img = new Image()
						img.src = res.path
						let canvas = document.createElement('canvas');
						let ctx = canvas.getContext('2d')
						canvas.width = canvasWidth / 2
						canvas.height = canvasHeight / 2
						ctx.drawImage(img, 0, 0, canvasWidth / 2, canvasHeight / 2)
						canvas.toBlob(fileSrc => {
							let imgSrc = window.URL.createObjectURL(fileSrc)
							console.log('压缩后', imgSrc)
							// _this.uploadFile(imgSrc)
							uni.uploadFile({
							  	url: `${apiUrl}/sys/common/upload`,
								header: {
									'X-Access-Token': getCookie('token')
								},
							  	filePath: imgSrc,
							  	name: 'file',
							  	success: res => {
									const data = JSON.parse(res.data)
									console.log('fail res:', data, data.message === 'Token失效，请重新登录');
									if (data.message === 'Token失效，请重新登录') {
										uni.showToast({
											icon: 'none',
											title: data.message
										})
										setTimeout(() => {
											uni.navigateTo({
												url: '../login/login'
											})
										}, 500)
									} else {
										// otherApis.getImgPreview + 
										const url = data.message;
										this.imgUploaded.push(url)
									}
							  	},
								fail: res => {
									uni.showToast({
										icon: 'none',
										title: res.errMsg,
									})
								}
							  });
						})
					}
				})
			},
            changeIndicatorDots(e){
            this.isYasuo = !this.isYasuo
            },
			// 随机生成字母 + 数字的6位数
			createCode() {
				let codeArr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];
				let length = 6;
				let code = "";
				for (let i = 0; i < length; i++) {
					let randomI = Math.floor(Math.random() * 36);
					code += codeArr[randomI];
				}
				return code;
			},
			cpimgOk(file) {
				let that = this
				that.src = file
				console.log(file)
			},
			cpimgErr(e) {
				console.log(e)
			},
            fileChange(arg){
				// this.$refs.cpimg._changImg()
				const e = arg[0];				
				if (this.imgList.length < e.length) {
					const array1 = difference(e, this.imgList);
					array1.forEach(item => {
						this.getImageInfo(item)
					})
					this.imgList  =cloneDeep(e)
				}
				if (arg[1] !== undefined) {
					this.imgUploaded.splice(arg[1], 1)
				}
			},
			chooseStar(e, index) { //点击评星
				if (index === 0) {
					this.sendDate.goodsGrade = e;
				} else if (index === 1) {
					this.sendDate.serviceGrade = e;
				} else if (index === 2) {
					this.sendDate.logisticsGrade = e;
				}
            },
            previewImage() { //预览图片
                uni.previewImage({
                    urls: this.imgList
                });
            },
            send() { //发送提交
				let backImgs = ''
				let len = this.imgUploaded.length;
				this.imgUploaded.map((item, index) => {
					console.log('item:', item)
					backImgs = backImgs + item + (index !== len - 1 && len > 1 ? ',': '');
				})
				otherApis.publishCommont({
					...this.sendDate,
					imgs: backImgs,
					orderId: this.orderInfo[0].orderId,
					goodsId: this.orderInfo[0].goodsId,
				}).then(res => {
					uni.showToast({
						icon: 'none',
						title: "发布成功"
					});
					setTimeout(() => {
						uni.reLaunch({
							url: '../personalCenter/personalCenter',
						});
					}, 10)
				})
			}
        }
    }
</script>

<style lang="scss" scoped>
    .page {
		.feedback-body {
			.feedback-textare {
				font-size: 28upx;	
			}
		}
    }
    .feedback-submit {
		box-shadow: 0upx 5upx 10upx rgba(0,0,0,0.4);
		margin: 20upx auto;
	    width: 70%;
		height: 80upx;
		border-radius: 80upx;
		background-color: #E80505;
		color: #fff;
		justify-content: center;
		align-items: center;
		&:hover {
		   background-color: #862732;
		}
	 }
    .input-view {
        font-size: 28upx;
    }
    .close-view{
        text-align: center;line-height:14px;height: 16px;width: 16px;border-radius: 50%;background: #FF5053;color: #FFFFFF;position: absolute;top: -6px;right: -4px;font-size: 12px;
    }
</style>
